package org.benjamin.lending.controller;

import java.util.List;

import javax.validation.Valid;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.benjamin.lending.domain.entity.BannerInfo;
import org.benjamin.lending.domain.form.ResultData;
import org.benjamin.lending.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "manager/banner")
public class ManagerBannerController {
	
	@Autowired
	private SystemService systemService;
	
	@RequestMapping(value = "index")
	public ModelAndView index() {
		ModelAndView modelAndView = new ModelAndView("admin.banner.index");
		List<BannerInfo> bannerInfos = this.systemService.findBannerList();
		for(BannerInfo bannerInfo : bannerInfos) {
			String base64Data = Base64.encodeBase64String(bannerInfo.getImagerContent().getContentData());
			bannerInfo.getImagerContent().setBase64Data(base64Data);
		}
		modelAndView.addObject("bannerInfos",bannerInfos);
		return modelAndView;
	}
	
	@GetMapping(value = "add")
	public ModelAndView toAdd() {
		ModelAndView modelAndView = new ModelAndView("admin.banner.add");
		modelAndView.addObject("bannerInfo",new BannerInfo());
		return modelAndView;
	}
	
	@ResponseBody
	@PostMapping(value = "add")
	public ResultData doAdd(@Valid BannerInfo bannerInfo,BindingResult bindingResult) {
		ResultData resultData = new ResultData();
		if(bindingResult.hasErrors()) {
			resultData.setMessage("提交参数有错误");
			resultData.setStatus(300);
			return resultData;
		}
		if(bannerInfo.getImagerContent().getId() == null) {
			resultData.setMessage("请先上传图片！");
			resultData.setStatus(300);
		}
		this.systemService.bannerSave(bannerInfo);
		resultData.setStatus(200);
		resultData.setMessage("Banner提交成功");
		return resultData;
	}

}
